# -*- encoding:utf-8 -*-
# @Time: 2022/10/26 14:32
# @Author : renyuxuan
# @Email: renyuxuan@maqu.com
# @File: serializers.py
# @Software: PyCharm

from rest_framework import serializers
from .models import Student,Classes

#序列化器优化
class StudentSerializer(serializers.ModelSerializer):
    # # 重写 默认展示classes=classes.id,classes=__str__
    # classes = serializers.StringRelatedField (label='班级')

    # 新增字段:source 返回模型对象的字段数据
    class_name = serializers.CharField(source='classes.name',read_only=True)


    class Meta:
        #model为Student的数据
        model = Student
        # 指定映射__all__所有的字段
        # fields = '__all__'
        # 页面不展示的数据如：不包含的字段 不映射的字段
        exclude = ['is_delete']
        #逻辑校验
        extra_kwargs = {
            'age':{'min_value':0,'max_value':100}
        }

    # 追加额外的逻辑校验，属性级别的，对单个字段进行校验
    # def validate_name(self,value):
    #     if 'mq' not in value.lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     return value

    #追加额外的逻辑校验，对象级别的，会把传入所有数据都传入date date={'name':'renyuxuan','age':31}
    # def validate(self,date):
    #     if 'mq' not in date['name'].lower():
    #         raise serializers.ValidationError('用户名需要包含mq')
    #     elif date['age'] < 18:
    #         raise serializers.ValidationError('未成年禁止访问')
    #     return date

class StudentSerializerSimple(serializers.ModelSerializer):
    class Meta:
        model = Student
        fields = ['id','name','age','sex']
class ClassesSerializer(serializers.ModelSerializer):
    # 序列化嵌套 管理器进行操作
    student_set = StudentSerializerSimple(many=True,read_only=True)

    class Meta:
        model = Classes
        # 指定映射__all__所有的字段
        # fields = '__all__'
        # 页面不展示的数据如：不包含的字段 不映射的字段
        exclude = ['is_delete']
